package com.tdam.CommunicationManager;

import java.util.ArrayList;
import java.util.Date;


import com.tdam.CommunicationManager.AnimatedActivity.InfoAdapter;



import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ViewAnimator;
//import android.graphics.PorterDuff;


public class Contacts extends AnimatedActivity {
	
	private ContactInfo selectedContact; 
	private TextView txtContactName;
	private EditText txtFinder;
	private TextWatcher filterTextWatcher;
	private ArrayAdapter<String> phoneArray;
	private ArrayAdapter<String> mailArray;
	private static final int CALL=0;
	private static final int SMS=1;
	private Dialog dialog; 
	private Dialog messageDialog;
	private Dialog associateAccountDialog;
	private ServerConnection server;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacs_view);
		views=(ViewAnimator) findViewById(R.id.viewContacts);
		views.setDisplayedChild(1);
		txtFinder=(EditText) findViewById(R.id.txtFinder);
		_adapter = new InfoAdapter<ContactInfo,ContactHolder>(this,R.layout.contacts_item,ContactHolder.class);

		filterTextWatcher = (new TextWatcher() {

		    public void afterTextChanged(Editable s) {
		    }

		    public void beforeTextChanged(CharSequence s, int start, int count,
		            int after) {
		    }

		    public void onTextChanged(CharSequence s, int start, int before,
		            int count) {
		        _adapter.getFilter().filter(s);
		    }
		});
		txtFinder.addTextChangedListener(filterTextWatcher);
		server=User.server;
        Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) 
        {
        	while (cur.moveToNext()) 
        	{	
        		ContactInfo newContact=new ContactInfo(cur.getLong(cur.getColumnIndex
        				(ContactsContract.Contacts._ID)),cur.getString(cur.getColumnIndex
        						(ContactsContract.Contacts.DISPLAY_NAME)));
        		_adapter.addItem(newContact);
        	}
        }
		getListView().setAdapter(_adapter);
		//getListView().setTextFilterEnabled(true);
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				onContactSelected(position);
			}
		});
		
		ListView lstPhones=(ListView) findViewById(R.id.lstPhones);
		phoneArray=new ArrayAdapter<String>(this,R.layout.info_data_item);
		lstPhones.setAdapter(phoneArray);
		lstPhones.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				onPhoneSelected(arg0.getItemAtPosition(position));
			}
		});
		
		ListView lstMail=(ListView) findViewById(R.id.lstMails);
		mailArray=new ArrayAdapter<String>(this,R.layout.info_data_item);
		lstMail.setAdapter(mailArray);
		lstMail.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				onMailSelected(position);
			}
		});
		
		txtContactName=(TextView) findViewById(R.id.txtName);
		TextView txtAllGroups= (TextView) findViewById(R.id.txtAll);
		txtAllGroups.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				nextView();
			}
		});
		Button btmGroups = (Button) findViewById(R.id.btmGroups);
		//btmGroups.getBackground().setColorFilter(0xFF4169E1, PorterDuff.Mode.MULTIPLY);
		btmGroups.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				previousView();
			}
		});
		Button btmBack = (Button) findViewById(R.id.btmBack);
		btmBack.setOnClickListener(new OnClickListener() {   
			
			@Override
			public void onClick(View v) {
				previousView();
			}
		});
        dialog = new Dialog(this);
        dialog.setContentView(R.layout.call_dialog);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		Button btmCall = (Button) dialog.findViewById(R.id.btmCall);
		btmCall.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				TextView txtPhoneNumber=(TextView) dialog.findViewById(R.id.txtPhoneNumber);
				send(CALL,txtPhoneNumber.getText().toString());
			}
		});	

		Button btmSms = (Button) dialog.findViewById(R.id.btmSms);
		btmSms.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				TextView txtPhoneNumber=(TextView) dialog.findViewById(R.id.txtPhoneNumber);
				send(SMS,txtPhoneNumber.getText().toString());
			}
		});
		Button btmCancel=(Button)dialog.findViewById(R.id.btmCancel);
		btmCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
			
		});

    	messageDialog=new Dialog(this);
    	messageDialog.setContentView(R.layout.web_mail_send_dialog);
    	messageDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);	    			
		Button btmSendMessage= (Button) messageDialog.findViewById(R.id.btmSendWebMessage);
		btmSendMessage.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				EditText txtMessage=(EditText) messageDialog.findViewById(R.id.txtMessage);
				String accountName=txtMessage.getText().toString();
				txtMessage.setText("");
				onSendWebMessage(accountName);

			}
		});
		Button btmCancelMessage=(Button)messageDialog.findViewById(R.id.btmCancelMessage);
		btmCancelMessage.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				((EditText) messageDialog.findViewById(R.id.txtMessage)).setText("");
				messageDialog.dismiss();
			}
			
		});
		
		associateAccountDialog=new Dialog(this);
		associateAccountDialog.setContentView(R.layout.web_mail_new_user);
		associateAccountDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);	    			
		Button btmAssociate= (Button) associateAccountDialog.findViewById(R.id.btmCreateWebUser);
		btmAssociate.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				EditText txtMessage=(EditText) associateAccountDialog.findViewById(R.id.txtUserName);
				String accountName=txtMessage.getText().toString();
				txtMessage.setText("");
				onAssociateAccount(accountName);

			}
		});
		Button btmCancelAssociation=(Button)associateAccountDialog.findViewById(R.id.btmCancelAssociation);
		btmCancelAssociation.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				associateAccountDialog.dismiss();
			}
			
		});
    	
		Button btmSendWebMail=(Button)findViewById(R.id.btmSendWebMail);
		btmSendWebMail.setOnClickListener(new OnClickListener() {   
			
			@Override
			public void onClick(View v) {
				onSendWebMail();
			}
		});		
	}

	@Override
	protected void onResume()
	{
		super.onResume();
        SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(getBaseContext());
        switch(Integer.parseInt(prefs.getString("lstContactsOrder","1")))
        {
        case 1:
        	_adapter.sort(new ContactNameAscComparator());
        	break;
        case 2:
        	_adapter.sort(new ContactNameDescComparator());
        }
        _adapter.notifyDataSetChanged();
	}
	
	public void onSendWebMessage(String message)
	{
		messageDialog.dismiss();
		WebMailInfo messageSend=new WebMailInfo(selectedContact.webUserName ,
				message, new Date(),false);
		boolean result=server.sendMessage(messageSend);
		String messageResult=getString(R.string.sendMessageFail);
		if(result)
		{
			messageResult=getString(R.string.sendMessageOk);
			ArrayList<WebMailInfo> messages=new ArrayList<WebMailInfo>();
			messages.add(messageSend);
			User.db.saveMessages(messages);
		}
		Toast.makeText(this,messageResult, Toast.LENGTH_SHORT).show();		
	}

	public void onAssociateAccount(String user)
	{
		associateAccountDialog.dismiss();
    	ContentValues newWebUser=new ContentValues();
    	newWebUser.put(ContactsContract.Data.RAW_CONTACT_ID, selectedContact.id);
    	newWebUser.put(ContactsContract.Data.MIMETYPE,DbInterface.MIMETYPE_WEBMAIL);
    	newWebUser.put(ContactsContract.Data.DATA1, user);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, newWebUser);    		
	}
	
	public void onContactSelected(int position)
	{
		ContentResolver myContentResolver=getContentResolver();
		selectedContact = (ContactInfo) _adapter.getItem(position);
		txtContactName.setText(selectedContact.name);
		phoneArray.clear();
		mailArray.clear();
		
		Cursor dataCursor = myContentResolver.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", 
 		new String[]{String.valueOf(selectedContact.id)}, null);
 	    while (dataCursor.moveToNext()) 
 	    {
 	    	phoneArray.add(dataCursor.getString(dataCursor.getColumnIndex(Phone.NUMBER)));
 	    } 
 	    dataCursor.close();
 	    
 	    dataCursor=myContentResolver.query(Email.CONTENT_URI,null,Email.CONTACT_ID +" = ?", 
		new String[]{String.valueOf(selectedContact.id)}, null);
	    while (dataCursor.moveToNext()) 
	    {
	    	mailArray.add(dataCursor.getString(dataCursor.getColumnIndex(Email.DATA)));
	    } 
	    dataCursor.close();
        Cursor photoCursor = myContentResolver.query(ContactsContract.Data.CONTENT_URI, null,
        		ContactsContract.Data.CONTACT_ID + " = ? AND " + 
        		ContactsContract.Data.MIMETYPE + " = ?",
        		new String[]{String.valueOf(selectedContact.id),
        		ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE}, null); 

        if (photoCursor.moveToFirst()) 
        { 
        	byte[] photo = photoCursor.getBlob(photoCursor.getColumnIndex
        			(ContactsContract.CommonDataKinds.Photo.PHOTO));
        	Bitmap photoBM = BitmapFactory.decodeByteArray(photo,0,photo.length);
        	((ImageView)findViewById(R.id.imgContact)).setImageBitmap(photoBM);
        }
        else
        	((ImageView)findViewById(R.id.imgContact)).setImageResource(R.drawable.contact_info);
 		photoCursor.close();	    	    
		
		nextView();
	}

	public void onPhoneSelected(Object number)
	{
		TextView txtPhoneNumber=(TextView) dialog.findViewById(R.id.txtPhoneNumber);
		txtPhoneNumber.setText((String)number);
		dialog.show();		
//		Toast.makeText(this, "Enviando sms", Toast.LENGTH_SHORT).show();
	}
	
	private void send(int option,String number)
	{
		dialog.dismiss();
		switch (option)
		{
			case 0:
				Intent callIntent = new Intent(Intent.ACTION_DIAL);
				callIntent.setData(Uri.parse("tel:" + number)); 
				startActivity(callIntent); 				
//				Toast.makeText(this, "Llamando", Toast.LENGTH_SHORT).show();
				break;
			case 1:
				Intent smsIntent = new Intent(Intent.ACTION_VIEW);
				//smsIntent.setData(Uri.parse("sms:")); 
				smsIntent.putExtra("address", number);
				smsIntent.setType("vnd.android-dir/mms-sms");
				startActivity(smsIntent); 				
//				Toast.makeText(this, "Enviando sms", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	public void onMailSelected(int position)
	{
		Intent callIntent = new Intent(Intent.ACTION_VIEW);
		callIntent.setData(Uri.parse("mailto:" + mailArray.getItem(position))); 
		startActivity(callIntent); 		
//		Toast.makeText(this, "Enviando mail", Toast.LENGTH_SHORT).show();
	}
	
	public void onSendWebMail()
	{
        Cursor contactCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null,
        		ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + 
        		ContactsContract.Data.MIMETYPE + " = ?",
        		new String[]{String.valueOf(selectedContact.id),
        		DbInterface.MIMETYPE_WEBMAIL}, null); 
        boolean needWebMailUser=true;
        if(contactCursor.moveToNext()) 
	    {
        	needWebMailUser=false;
        	selectedContact.webUserName=(contactCursor.getString
        			(contactCursor.getColumnIndex(ContactsContract.Data.DATA1)));
        	messageDialog.show();
	    } 
        contactCursor.close();
        if(needWebMailUser)
        {
        	associateAccountDialog.show();
        }
	    
	}

	protected void onDestroy() {
	    super.onDestroy();
	    txtFinder.removeTextChangedListener(filterTextWatcher);
	}	
}	
	


